package com.qf.mybatis02.utils;

import com.qf.mybatis02.entity.Book;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BookReader {

    /**
     * 每次调用readBatch方法时，读取的书的数量
     * 默认值1000
     */
    private Integer batchNum = 1000;

    /**
     * 从哪个文件中读取数据
     */
    private String filepath;

    /**
     * 注意，为了能够持续读取同一个文件，需要把bufferedReader对象作为实例属性
     */
    private BufferedReader bufferedReader;

    public BookReader(String filepath) throws FileNotFoundException {
        this.filepath = filepath;

        // 初始化 bufferedReader
        this.bufferedReader = new BufferedReader(new FileReader(filepath));
    }

    public BookReader(Integer batchNum, String filepath) throws FileNotFoundException {
        this.batchNum = batchNum;
        this.filepath = filepath;

        // 初始化 bufferedReader
        this.bufferedReader = new BufferedReader(new FileReader(filepath));
    }


    /**
     * 读一批书。数量由batchNum决定
     * @return
     */
    public List<Book> readBatch() throws IOException {

        final ArrayList<Book> books = new ArrayList<>();

        String line = null;

        while ( ( line = bufferedReader.readLine() )!=null ){

            // 类型转换： String ---->  book对象
            // ajdbqkcph011vpmkea7l,h82w53s96x,n3hmnhezbgqu0wb0ph9b0eng6,297586
            final Book book = Book.csvToBook(line);
            books.add(book);

            if (books.size()==batchNum){ // 读够一批的数量了
                return books;
            }
        }


        return books;

    }

    /**
     * 关闭相关的资源
     */
    public void close() throws IOException {

        this.bufferedReader.close();

    }

}
